import matplotlib.pyplot as plt
import numpy as np


def saveImg(x, y, filename):
    plt.plot(x, y)
    plt.xlabel('f')
    plt.ylabel('fudu')
    plt.grid(True)
    plt.savefig(filename+".fft.png")
    plt.close('all')

def return1(data):
    HE = data.sum()
    ndata = data
    if(HE != 0):
        ndata = ndata/HE
    return ndata

def fftAll(filename, logpath):
    filee = open(filename)
    i = 1
    for line in filee:
        data = []
        rawdata = line.rsplit(sep=',')
        fname = logpath + rawdata[0]
        data = [int(x) for x in rawdata[1:]]
        data = np.array(data)

        data = data - data.sum()/len(data) # 去直流分量
        saveImg(np.linspace(0,len(data), len(data)), data, fname + ".data")
        
        fftdata = np.fft.fft(data)
        fdp = np.abs(fftdata)

        # # 归一化
        nfdp = return1(fdp)

        # # 滤波 留 24 到 110
        nfdp = nfdp[24:111]
        
        huanyuandu = nfdp[np.argsort(nfdp)][len(nfdp)-5:].sum()


        print(i, fname, huanyuandu)
        i = i+1
        x = np.linspace(0, len(nfdp) - 1, len(nfdp))
        name = fname + '__[' + str(huanyuandu) + ']__'
        print(name)
        saveImg(x, nfdp, name)

    filee.close()

# fftAll("./weishuju/weishuju.txt", "./weilog/")
fftAll("/Users/wangsiyuan/code/leecode/js/learnangular/ohters/view20160731.txt", "./log/")